<!DOCTYPE html>
<title>Test the initial state of AudioContext's with the autoplay policy</title>
<script src='../../resources/testharness.js'></script>
<script src='../../resources/testharnessreport.js'></script>
<script>
function activateDocument(t) {
  return new Promise((resolve, reject) => {
    chrome.gpuBenchmarking.pointerActionSequence([
      {
        source: 'mouse',
        actions: [
          { name: 'pointerDown', x: 1, y: 1 },
          { name: 'pointerUp' },
        ],
      }
    ], t.step_func(resolve));
  });
}

function setup(t) {
  const autoplayIgnoresWebAudioEnabled =
      internals.runtimeFlags.autoplayIgnoresWebAudioEnabled;

  internals.runtimeFlags.autoplayIgnoresWebAudioEnabled = false;
  internals.settings.setAutoplayPolicy('document-user-activation-required');

  t.add_cleanup(() => {
    internals.runtimeFlags.autoplayIgnoresWebAudioEnabled =
        autoplayIgnoresWebAudioEnabled;
    internals.settings.setAutoplayPolicy('no-user-gesture-required');
  });
}

promise_test(t => {
  setup(t);

  return new Promise((resolve) => {
    const context = new OfflineAudioContext(1, 4000, 3000);
    context.startRendering();
    context.suspend(1);
    resolve();

    return context.resume().then(t.step_func(() => {
      assert_equals(context.state, 'running');
    }));
  });
}, 'OfflineAudioContext can always be resumed.');

promise_test(async (t) => {
  setup(t);

  let resumePromises = [ null, null ];
  const context = new AudioContext();
  let wasResumed = false;

  resumePromises[0] = context.resume().then(t.step_func(() => {
    wasResumed = true;
  }));

  await activateDocument(t);

  assert_false(wasResumed);

  // Start playback on a node so the audio context renders something.
  const oscillator = context.createOscillator();
  oscillator.connect(context.destination);
  oscillator.start();

  // This call to resume will activate the AudioContext.
  resumePromises[1] = context.resume();

  return Promise.all(resumePromises).then(t.step_func(() => {
    assert_true(wasResumed);
  }));
}, 'AudioContext.resume() resolves if/when the context starts.');
</script>
